import decimal

from django.db.models import Q
from django.shortcuts import render

from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse, HttpResponse
from ..models import *
from ..utils import jwtUtils
from ..utils.fileSystem import uploadFileAssets, removeFile
from ..utils.func import filterImageUrl, getCurrentTime, stripImageUrl, getDecimalData, filterDataListImageUrl, \
    removeDataListImageUrl, isEmpty
from ..utils.jsonSerialize import serialize_models
import time

from ..utils.paramsValidator import RulesValidate


# 一、 用户相关
# 查询用户
def userSearch(request):
    data = request.GET.dict ()
    phone = data.get('phone',None)
    is_delete = data.get('is_delete',None)
    request_Data = {}
    if phone:
        request_Data["phone__icontains"] = phone
    if is_delete:
        # request_Data["is_delete__icontains"] = is_delete
        request_Data["is_delete"] = is_delete
    data_list = UserMsg.objects.filter(**request_Data)
    data_list = serialize_models(data_list)
    filterDataListImageUrl(request,data_list,'avatar_url')
    return JsonResponse ({'msg': '查询用户信息成功！','data':data_list, 'code': 200})

# 更新用户信息
def userUpdate(request):
    data = request.POST.dict()
    user_id = data.get('id',None)
    goods_obj = UserMsg.objects.filter(id=user_id)
    # 添加注册时间
    data = {
        'type': data.get("type",None),
        'update_time': getCurrentTime()
    }
    goods_obj.update(**data)
    return JsonResponse({'msg': '修改用户信息成功！', 'code': 200})

# 二、商品相关
# 查询商品
def goodsSearch(request):
    data = request.GET.dict ()
    name = data.get('name',None)
    status = data.get('status',None)
    is_has_count = data.get('is_has_count',None)
    request_Data = {}
    if status:
        request_Data["status"] = status
    if is_has_count:
        if is_has_count == '1':
            request_Data["max_count__gt"] = 0
        elif is_has_count == '0':
            request_Data["max_count"] = 0
    # 执行查询
    data_list = None
    if name:
        # request_Data["name__icontains"] = name
        # request_Data["keywords__icontains"] = name
        data_list = Goods.objects.filter(Q(**request_Data) & (Q(name__icontains=name) | Q(keywords__icontains=name) | Q(description__icontains=name))).order_by("-status")
    else:
        data_list = Goods.objects.filter(**request_Data).order_by("-status")
    data_list = serialize_models(data_list)
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'banner_url')
    return JsonResponse ({'msg': '查询用户信息成功！','data':data_list, 'code': 200})

# 新增商品
def goodsAdd(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'name': '商品名称',
        'description': '商品描述',
        'content': '商品内容',
        'price': '商品价格',
        'max_count': '最大数量',
        'keywords': '关键词',
    })
    if res: return res
    # 添加注册时间
    data['create_time'] = getCurrentTime()
    # 如果有头像上传，则保存头像。
    filename = uploadFileAssets(request,'banner')
    data["banner_url"] = filename
    data['status'] = '1'
    # 去除字段
    data.pop("file",None)
    resObj = Goods(**data)
    resObj.save()
    if resObj.id != None:
        return JsonResponse ({'msg': '新增商品成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '新增商品失败！请重试', 'code': 200})

# 修改商品
def goodsUpdate(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken", None)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'name': '商品名称',
        'description': '商品描述',
        'content': '商品内容',
        'price': '商品价格',
        'max_count': '最大数量',
        'keywords': '关键词',
        'id': '商品Id',
    })
    if res: return res
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '修改失败！商品不存在！', 'code': 403})
    else:
        # 处理商品路径
        stripImageUrl(request,data,'banner_url')
        # 如果有图片上传，则更新图片
        filename = uploadFileAssets(request, 'banner')
        if filename != None:
            # 删除上一张图片
            removeFile(goods_obj_filter.banner_url)
            # 更新图片
            data["banner_url"] = filename
        goods_obj.update(**data)
        return JsonResponse({'msg': '修改商品成功！', 'code': 200})

# 删除商品
def goodsDelete(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request, 'POST', {
        'id': '商品Id',
    })
    if res: return res
    status = data.get('status',None)
    goods_id = data.get('id',None)
    goods_obj = Goods.objects.filter(id=goods_id)
    # 序列化数据
    data_list = serialize_models(goods_obj)
    res = goods_obj.delete()
    if res[0] > 0:
        # 移除图片
        removeDataListImageUrl(data_list,'banner_url')
        return JsonResponse({'msg': '删除商品成功！', 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已删除！', 'code': 200})

# 上架/下架商品
def goodsUpload(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request, 'POST', {
        'status': '商品状态',
        'id': '商品Id',
    })
    if res: return res
    status = data.get('status',None)
    goods_id = data.get('id',None)
    goods_obj = Goods.objects.filter(id=goods_id)
    # 添加注册时间
    data = {
        'status': status,
        'update_time': getCurrentTime()
    }
    name = '上架' if status == '1' else '下架'
    res = goods_obj.update(**data)
    if res > 0:
        return JsonResponse({'msg': name+'商品成功！', 'code': 200})
    else:
        return JsonResponse({'msg': name+'商品失败！', 'code': 403})

# 三、积分相关
# 查询用户
def creditSearch(request):
    data = request.GET.dict ()
    value = data.get('value',None)
    status = data.get('status',None)
    user_id = data.get('user_id',None)
    name = data.get('name',None)
    request_Data = {}
    if status:
        request_Data["status"] = status
    if value:
        request_Data["value"] = value
    if user_id:
        request_Data["credit_user_id"] = user_id
    # 执行查询
    data_list = None
    if name:
        # request_Data["name__icontains"] = name
        # request_Data["keywords__icontains"] = name
        data_list = Credits.objects.filter(Q(**request_Data) & (Q(name__icontains=name) | Q(description__icontains=name)))
    else:
        data_list = Credits.objects.filter(Q(**request_Data) & (~Q(status='0'))).order_by("status")
    # 序列化数据集对象
    data_list = serialize_models(data_list,['credit_user'])
    filterDataListImageUrl(request,data_list,'avatar_url','credit_user')
    return JsonResponse ({'msg': '查询积分信息成功！','data':data_list, 'code': 200})


# 赠送积分
def creditSend(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'name': '积分名称',
        'description': '积分描述',
        'value': '积分值',
        # 'credit_user_id': '赠送用户ID',
        'credit_phone':'用户手机号码'
    })
    if res: return res
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(phone=data['credit_phone'])
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse({'msg': '赠送用户不存在！无法赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse({'msg': '赠送用户已注销！无法赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse({'msg': '赠送用户已封禁！请解封后再赠送', 'code': 403})
    credit_user_id = user_obj_filter.id
    data['credit_user_id'] = credit_user_id
    data.pop('credit_phone',None)
    # credit_user_id = data.get('credit_user_id',None)
    # 添加注册时间
    data['create_time'] = getCurrentTime()
    data['status'] = '1'
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(id=credit_user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse ({'msg': '赠送用户不存在！无法赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse ({'msg': '赠送用户已注销！无法赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse ({'msg': '赠送用户已封禁！请解封后再赠送', 'code': 403})
    resObj = Credits(**data)
    resObj.save()
    # 累加赠送积分
    newAmount = (user_obj_filter.amount + getDecimalData(data['value']))
    if resObj.id != None:
        # 这里不验证是否新增成功
        res = user_obj.update(amount=newAmount)
        return JsonResponse ({'msg': '赠送积分成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '赠送积分失败！请重试', 'code': 200})

# 撤销赠送积分
def creditRepeal(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'id': 'ID',
    })
    if res: return res
    credit_id = data.get('id',None)
    credit_obj = Credits.objects.filter(id=credit_id)
    credit_obj_filter = credit_obj.first()
    if credit_obj_filter == None:
        return JsonResponse ({'msg': '当前赠送信息不存在', 'code': 403})
    elif credit_obj_filter.status == '0':
        return JsonResponse ({'msg': '当前赠送已撤销，请勿重复处理', 'code': 403})
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(id=credit_obj_filter.credit_user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse ({'msg': '赠送用户不存在！无法撤销赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse ({'msg': '赠送用户已注销！无法撤销赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse ({'msg': '赠送用户已封禁！请解封后再撤销赠送', 'code': 403})
    # 添加注册时间
    data = {
        'status': '0',
        'update_time': getCurrentTime()
    }
    res = credit_obj.update(**data)
    # 累加赠送积分
    newAmount = (user_obj_filter.amount - getDecimalData(credit_obj_filter.value))
    if res > 0:
        # 这里不验证是否新增成功
        res = user_obj.update(amount=newAmount)
        return JsonResponse({'msg': '撤销积分赠送成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '撤销积分赠送失败！请重试', 'code': 403})

# 四、优惠券相关
# 查询用户
def couponSearch(request):
    data = request.GET.dict ()
    value = data.get('value',None)
    level_price = data.get('level_price',None)
    status = data.get('status',None)
    user_id = data.get('user_id',None)
    name = data.get('name',None)
    start_time = data.get('start_time',None)
    end_time = data.get('end_time',None)
    request_Data = {}
    if status:
        request_Data["status"] = status
    if value:
        request_Data["value"] = value
    if level_price:
        request_Data["level_price"] = level_price
    if user_id:
        request_Data["coupon_user_id"] = user_id
    if start_time:
        request_Data["start_time__gte"] = start_time
    if end_time:
        request_Data["end_time__lte"] = end_time
    # 执行查询
    data_list = None
    if name:
        # request_Data["name__icontains"] = name
        # request_Data["keywords__icontains"] = name
        data_list = Coupons.objects.filter(Q(**request_Data) & (Q(name__icontains=name) | Q(description__icontains=name))).order_by("status")
    else:
        data_list = Coupons.objects.filter(Q(**request_Data) & (~Q(status='0'))).order_by("status")
    # 序列化数据集对象
    data_list = serialize_models(data_list,['coupon_user'])
    filterDataListImageUrl(request,data_list,'avatar_url','coupon_user')
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'coupon_url')
    return JsonResponse ({'msg': '查询优惠券信息成功！','data':data_list, 'code': 200})


# 赠送优惠券
def couponSend(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'name': '优惠券名称',
        'description': '优惠券描述',
        'start_time': '开始时间',
        'end_time': '结束时间',
        'value': '优惠积分',
        'level_price': '用券门槛积分',
        # 'coupon_user_id':'赠送用户id'
        'coupon_phone':'用户手机号码'
    })
    if res: return res
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(phone=data['coupon_phone'])
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse({'msg': '赠送用户不存在！无法赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse({'msg': '赠送用户已注销！无法赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse({'msg': '赠送用户已封禁！请解封后再赠送', 'code': 403})
    coupon_user_id = user_obj_filter.id
    data['coupon_user_id'] = coupon_user_id
    data.pop('coupon_phone',None)
    # coupon_user_id = data.get('coupon_user_id',None)
    # 如果有头像上传，则保存头像。
    filename = uploadFileAssets(request, 'coupon')
    data["coupon_url"] = filename
    # 添加注册时间
    data['create_time'] = getCurrentTime()
    data['status'] = '1'
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(id=coupon_user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse ({'msg': '赠送用户不存在！无法赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse ({'msg': '赠送用户已注销！无法赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse ({'msg': '赠送用户已封禁！请解封后再赠送', 'code': 403})
    resObj = Coupons(**data)
    resObj.save()
    if resObj.id != None:
        # 这里不验证是否新增成功
        return JsonResponse ({'msg': '赠送优惠券成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '赠送优惠券失败！请重试', 'code': 200})

# 撤销赠送优惠券
def couponRepeal(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'id': 'ID',
    })
    if res: return res
    coupon_id = data.get('id',None)
    coupon_obj = Coupons.objects.filter(id=coupon_id)
    coupon_obj_filter = coupon_obj.first()
    if coupon_obj_filter == None:
        return JsonResponse ({'msg': '当前赠送信息不存在', 'code': 403})
    elif coupon_obj_filter.status == '0':
        return JsonResponse ({'msg': '当前赠送已撤销，请勿重复处理', 'code': 403})
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(id=coupon_obj_filter.coupon_user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse ({'msg': '赠送用户不存在！无法撤销赠送', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse ({'msg': '赠送用户已注销！无法撤销赠送', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse ({'msg': '赠送用户已封禁！请解封后再撤销赠送', 'code': 403})
    # 添加注册时间
    data = {
        'status': '0',
        'update_time': getCurrentTime()
    }
    res = coupon_obj.update(**data)
    # 累加赠送优惠券
    if res > 0:
        return JsonResponse({'msg': '撤销优惠券赠送成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '撤销优惠券赠送失败！请重试', 'code': 403})


# 五、通知相关
# 查询通知
def noticeSearch(request):
    data = request.GET.dict ()
    title = data.get('title',None)
    user_id = data.get('user_id', None)
    start_time = data.get('start_time', None)
    end_time = data.get('end_time', None)
    request_Data = {}
    if user_id:
        request_Data["notice_user_id"] = user_id
    if start_time:
        request_Data["start_time__gte"] = start_time
    if end_time:
        request_Data["end_time__lte"] = end_time
    # 执行查询
    data_list = None
    if title:
        # request_Data["title__icontains"] = title
        # request_Data["keywords__icontains"] = title
        data_list = Notices.objects.filter(Q(**request_Data) & (Q(title__icontains=title) | Q(content__icontains=title)))
    else:
        data_list = Notices.objects.filter(**request_Data)
    # 序列化数据集对象
    data_list = serialize_models(data_list, ['notice_user'])
    filterDataListImageUrl(request, data_list, 'avatar_url', 'notice_user')
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'notice_url')
    return JsonResponse ({'msg': '查询通知成功！','data':data_list, 'code': 200})

# 新增通知
def noticeAdd(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'title': '标题',
        'content': '内容',
        'start_time': '开始时间',
        'end_time': '结束时间',
    })
    if res: return res
    notice_phone = data.get("notice_phone",None)
    if not isEmpty(notice_phone):
        # 检查用户账号是否正常
        user_obj = UserMsg.objects.filter(phone=data['notice_phone'])
        user_obj_filter = user_obj.first()
        if user_obj_filter == None:
            return JsonResponse({'msg': '用户不存在！无法通知', 'code': 403})
        elif user_obj_filter.is_delete == '1':
            return JsonResponse({'msg': '用户已注销！无法通知', 'code': 403})
        elif user_obj_filter.type == '0':
            return JsonResponse({'msg': '用户已封禁！请解封后再通知', 'code': 403})
        data['notice_user_id'] = user_obj_filter.id
        data.pop('notice_phone',None)
    # 添加注册时间
    data['create_time'] = getCurrentTime()
    # 如果有头像上传，则保存头像。
    filename = uploadFileAssets(request,'notice')
    data["notice_url"] = filename
    # 去除字段
    data.pop("file",None)
    data.pop("notice_phone",None)
    resObj = Notices(**data)
    resObj.save()
    if resObj.id != None:
        return JsonResponse ({'msg': '新增通知成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '新增通知失败！请重试', 'code': 200})

# 修改通知
def noticeUpdate(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken", None)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'title': '标题',
        'content': '内容',
        'start_time': '开始时间',
        'end_time': '结束时间',
        'id': 'ID',
    })
    if res: return res
    # 先检测数据表
    notice_obj = Notices.objects.filter(id=data['id'])
    notice_obj_filter = notice_obj.first()
    if not notice_obj_filter:
        return JsonResponse({'msg': '修改失败！通知不存在！', 'code': 403})
    else:
        # 处理商品路径
        stripImageUrl(request,data,'notice_url')
        # 如果有图片上传，则更新图片
        filename = uploadFileAssets(request, 'notice')
        if filename != None:
            # 删除上一张图片
            removeFile(notice_obj_filter.notice_url)
            # 更新图片
            data["notice_url"] = filename
        notice_obj.update(**data)
        return JsonResponse({'msg': '修改通知成功！', 'code': 200})

# 删除通知
def noticeDelete(request):
    data = request.POST.dict ()
    notice_id = data.get('id',None)
    notice_obj = Notices.objects.filter(id=notice_id)
    # 序列化数据
    data_list = serialize_models(notice_obj)
    res = notice_obj.delete()
    if res[0] > 0:
        # 移除图片
        removeDataListImageUrl(data_list,'notice_url')
        return JsonResponse({'msg': '删除通知成功！', 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已删除！', 'code': 200})

# 六、兑换相关
# 查询商品
def exchangeSearch(request):
    data = request.GET.dict ()
    user_id = data.get('user_id',None)
    status = data.get('status',None)
    coupon_amount = data.get('coupon_amount',None)
    min_amount = data.get('min_amount',None)
    min_count = data.get('min_count',None)
    is_has_coupon = data.get('is_has_coupon',None)
    start_time = data.get('start_time',None)
    end_time = data.get('end_time',None)
    request_Data = {}
    if status:
        request_Data["status"] = status
    if user_id:
        request_Data["user_id"] = user_id
    if coupon_amount:
        request_Data["coupon_amount"] = coupon_amount
    if is_has_coupon:
        if is_has_coupon == '1':
            request_Data["coupon_id__isnull"] = False
        elif is_has_coupon == '0':
            request_Data["coupon_id__isnull"] = True
    if min_amount:
        request_Data['amount__gte'] = getDecimalData(min_amount)
    if min_count:
        request_Data['count__gte'] = int(min_count)
    if start_time:
        request_Data['create_time__gte'] = start_time
    if end_time:
        request_Data['create_time__lte'] = end_time
    # 执行查询
    data_list = Exchanges.objects.filter(**request_Data)
    # 序列化数据集对象
    data_list = serialize_models(data_list,['user'])
    filterDataListImageUrl(request,data_list,'avatar_url','user')
    return JsonResponse ({'msg': '查询兑换信息成功！','data':data_list, 'code': 200})

# 兑换详情
def exchangeInfo(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'id': 'ID',
    })
    if res: return res
    exchange_id = data.get('id',None)
    exchange_obj = ExchangeGoods.objects.filter(exchange_id=exchange_id)
    # 序列化数据
    data_list = serialize_models(exchange_obj)
    # 处理图片路径
    filterDataListImageUrl(request,data_list,'banner_url')
    return JsonResponse({'msg': '获取详情成功！','data': data_list, 'code': 200})

# 确认兑换
def exchangeConfirm(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'status': '状态',
        'id': '兑换ID',
    })
    if res: return res
    # 先检测数据表
    exchange_id = data.get('id',None)
    status = data.get('status',None)
    exchange_obj = Exchanges.objects.filter(id=exchange_id)
    exchange_obj_filter = exchange_obj.first()
    if not exchange_obj_filter:
        return JsonResponse({'msg': '兑换失败！兑换不存在！', 'code': 403})
    if exchange_obj_filter.status == '1':
        return JsonResponse({'msg': '兑换失败！该兑换已完成！', 'code': 403})
    if exchange_obj_filter.status == '2':
        return JsonResponse({'msg': '兑换失败！该兑换已拒绝！', 'code': 403})
    # 检查用户账号是否正常
    user_obj = UserMsg.objects.filter(id=exchange_obj_filter.user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse({'msg': '用户不存在！无法兑换', 'code': 403})
    elif user_obj_filter.is_delete == '1':
        return JsonResponse({'msg': '用户已注销！无法兑换', 'code': 403})
    elif user_obj_filter.type == '0':
        return JsonResponse({'msg': '用户已封禁！请解封后再兑换', 'code': 403})
    # 检查优惠券是否正常
    coupon_obj = None
    if exchange_obj_filter.coupon_id != None:
        coupon_obj = Coupons.objects.filter(id=exchange_obj_filter.coupon_id)
        coupon_obj_filter = coupon_obj.first()
        if coupon_obj_filter == None:
            return JsonResponse({'msg': '优惠券不存在！无法兑换', 'code': 403})
    name = '确认' if status == '1' else '拒绝'
    res = exchange_obj.update(status=status,approve_time=getCurrentTime())
    if res > 0:
        # 如果是1,则扣除用户积分
        if status == '1':
            after_amount = exchange_obj_filter.after_amount
            # 累加赠送积分
            newAmount = (user_obj_filter.amount - getDecimalData(after_amount))
            # 这里不验证是否新增成功
            res2 = user_obj.update(amount=newAmount)
        # 如果是2，则返还优惠券，和商品库存
        else:
            if exchange_obj_filter.coupon_id != None:
                res2 = coupon_obj.update(status='0',update_time=getCurrentTime())
            exchange_goods_obj = ExchangeGoods.objects.filter(exchange_id=exchange_id)
            # 序列化数据
            data_list = serialize_models(exchange_goods_obj)
            for item in data_list:
                try:
                    if item['goods_id'] != None:
                        goods_obj = Goods.objects.filter(id=item['goods_id'])
                        goods_obj_filter = goods_obj.first()
                        if goods_obj_filter != None:
                            max_count = int(goods_obj_filter.max_count) + int(item['goods_count'])
                            # 这里不考虑并发性问题
                            res3 = goods_obj.update(max_count=max_count,update_time=getCurrentTime())
                except Exception as e:
                    print("出现异常",e)
        return JsonResponse({'msg': name+'兑换成功！', 'code': 200})
    else:
        return JsonResponse({'msg': name+'兑换失败！', 'code': 403})

# 用户撤销兑换
def exchangeCancel(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'id': '兑换ID',
    })
    if res: return res
    # 先检测数据表
    exchange_id = data.get('id',None)
    exchange_obj = Exchanges.objects.filter(id=exchange_id)
    exchange_obj_filter = exchange_obj.first()
    if not exchange_obj_filter:
        return JsonResponse({'msg': '撤销失败！兑换不存在！', 'code': 403})
    if exchange_obj_filter.status == '1':
        return JsonResponse({'msg': '撤销失败！该兑换已完成！', 'code': 403})
    if exchange_obj_filter.status == '2':
        return JsonResponse({'msg': '撤销失败！该兑换已拒绝！', 'code': 403})
    ext_msg = ''
    # 检查优惠券是否正常
    if not isEmpty(exchange_obj_filter.coupon_id):
        coupon_obj = Coupons.objects.filter(id=exchange_obj_filter.coupon_id)
        coupon_obj_filter = coupon_obj.first()
        if coupon_obj_filter == None:
            return JsonResponse({'msg': '优惠券不存在！无法撤销', 'code': 403})
        # 返还优惠券
        res1 = coupon_obj.update(status='1',update_time=getCurrentTime())
        ext_msg = '，优惠券已返还'
    # 清除兑换头和兑换体信息
    res2 = exchange_obj.delete()
    if res2[0] > 0:
        exchange_goods_obj = ExchangeGoods.objects.filter(exchange_id=exchange_id)
        res3 = exchange_goods_obj.delete()
        return JsonResponse({'msg': '撤销商品兑换成功！'+ext_msg, 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已删除！', 'code': 200})

# 七、推荐相关
# 查询商品列表
def goodsRecommendSearch(request):
    data = request.GET.dict ()
    name = data.get('name',None)
    start_price = data.get('start_price',None)
    end_price = data.get('end_price',None)
    # 默认获取推荐类型
    request_Data = {}
    if start_price:
        request_Data["price__gte"] = start_price
    if end_price:
        request_Data["price__lte"] = end_price
    # 执行获取
    data_list = None
    if name:
        # request_Data["name__icontains"] = name
        # request_Data["keywords__icontains"] = name
        data_list = GoodsCategory.objects.filter(goods_id__in=(
            Goods.objects.filter(Q(**request_Data) & (Q(name__icontains=name) | Q(keywords__icontains=name) | Q(description__icontains=name))).values("id")
        ),type='2').order_by('order','create_time')
    else:
        data_list = GoodsCategory.objects.filter(goods_id__in=(
            Goods.objects.filter(**request_Data).values("id")
        ),type='2').order_by('order','create_time')
    # 序列化数据集对象
    data_list = serialize_models(data_list, ['goods'])
    filterDataListImageUrl(request, data_list, 'banner_url', 'goods')
    return JsonResponse ({'msg': '获取商品推荐成功！','data':data_list, 'code': 200})

# 新增商品推荐
def goodsRecommendAdd(request):
    data = request.POST.dict()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'goods_id': '商品名称',
        'order': '排序',
        'type': '类型',
    })
    if res: return res
    # 添加注册时间
    data['create_time'] = getCurrentTime()
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['goods_id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '添加失败！商品不存在！', 'code': 403})
    resObj = GoodsCategory(**data)
    resObj.save()
    if resObj.id != None:
        return JsonResponse ({'msg': '新增商品推荐成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '新增商品推荐失败！请重试', 'code': 200})

# 删除商品推荐
def goodsRecommendDelete(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request, 'POST', {
        'id': '商品推荐Id',
    })
    if res: return res
    category_id = data.get('id',None)
    category_obj = GoodsCategory.objects.filter(id=category_id)
    # 序列化数据
    data_list = serialize_models(category_obj)
    res = category_obj.delete()
    if res[0] > 0:
        return JsonResponse({'msg': '删除商品推荐成功！', 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已删除！', 'code': 200})
